using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

[CustomEditor(typeof(DynamicObject))]
public class FieldDefinitionWindow : Editor
{
    private List<FieldDefinition> _fields = new ();
    private Vector2 _scrollPosition;

    private void OnEnable()
    {
        _fields.AddRange(((DynamicObject)target).definitions);
    }

    public override void OnInspectorGUI()
    {
        if (Application.isPlaying)
        {
            RuntimePanel();
        }
        else
        {
            //EditPanel();
        }

    }

    private void RuntimePanel()
    {
        EditorGUILayout.HelpBox("运行时不可编辑", MessageType.Warning);
        //显示已有的字段
        DynamicObject dynamicObject = (DynamicObject)target;
        foreach (var (key, value) in dynamicObject.GetFields())
        {
            GUILayout.Label($"{key}: {value.GetValue()}");
        }
    }

    private void EditPanel()
    {
        _scrollPosition = EditorGUILayout.BeginScrollView(_scrollPosition);
        
        EditorGUILayout.LabelField("字段定义", EditorStyles.boldLabel);
        
        for (int i = 0; i < _fields.Count; i++)
        {
            DrawFieldDefinition(i);
        }
        
        if (GUILayout.Button("添加字段"))
        {
            _fields.Add(new FieldDefinition("NewField", FieldType.Int));
        }
        
        EditorGUILayout.EndScrollView();
        
        if (GUILayout.Button("保存定义"))
        {
            SaveFieldDefinitions();
        }
    }
    
    private void DrawFieldDefinition(int index)
    {
        var field = _fields[index];
        
        EditorGUILayout.BeginVertical("box");
        
        field.Name = EditorGUILayout.TextField( "字段名", field.Name);
        field.Type = (FieldType)EditorGUILayout.EnumPopup("类型", field.Type);
        field.DefaultValue = field.Type switch
        {
            FieldType.Int => EditorGUILayout.IntField("默认值", int.TryParse(field.DefaultValue, out var intDefaultValue) ? intDefaultValue : 0).ToString(),
            FieldType.Bool => EditorGUILayout.Toggle("默认值",bool.TryParse(field.DefaultValue,out var boolDefaultValue) && boolDefaultValue).ToString(),
            FieldType.Float => EditorGUILayout.FloatField("默认值",float.TryParse(field.DefaultValue,out var floatDefaultValue) ?floatDefaultValue : 0f ).ToString(),
        };
        
        if (GUILayout.Button("删除"))
        {
            _fields.RemoveAt(index);
        }
        
        EditorGUILayout.EndVertical();
    }
    
    private void SaveFieldDefinitions()
    {
        var obj = (DynamicObject)target;
        
        Debug.Log($"原来有{obj.definitions.Count}个字段");
        
        obj.definitions.Clear();
        for (int i = 0; i < _fields.Count; i++)
        {
            obj.definitions.Add(_fields[i]);
        }
        
        
        // 标记对象为已修改
        EditorUtility.SetDirty(obj);
        
        Debug.Log($"保存了 {obj.definitions.Count} 个字段定义");
    }
}
